import React from 'react';
import 'braft-editor/dist/index.css';
// 引入编辑器组件
import BraftEditor from 'braft-editor';
// 引入编辑器样式
import 'braft-editor/dist/index.css';
import styles from './index.less';
import AliyunOSSUpload from '../ALiYunOSSUpload';
import { ContentUtils } from 'braft-utils';
import { Button } from 'antd';

export default class EditorDemo extends React.Component<any, any> {
  // BraftEditor 详细文档： https://www.yuque.com/braft-editor/be/lzwpnr
  state = {
    // 创建一个空的editorState作为初始值
    editorState: BraftEditor.createEditorState(null),
  };

  // 输入时触发
  handleEditorChange = (editorState: any) => {
    this.setState({ editorState });
    // 获取 HTML 格式的内容
    const content = editorState.toHTML();
    console.log(editorState);
    console.log(content);

    // 因为 editorState.toHTML() 在不输入时也会形成空的 p 标签，使用 editorState.isEmpty() 判断输入值是否为空， 不为空时 再进行传值
    if (!editorState.isEmpty()) {
      // 调用父组件的方法，将编辑器输入内容传递回去，用于做表单验证
      this.props.setDetails(content);
    }

    if (!editorState.isEmpty()) {
      // 调用父组件的方法，将编辑器输入内容传递回去，用于做表单验证
      this.props.setDetails(content);
    }
  };

  // 上传图片后, 在富文本框内显示
  insertImage = (url: string) => {
    this.setState({
      editorState: ContentUtils.insertMedias(this.state.editorState, [
        {
          type: 'IMAGE',
          url,
        },
      ]),
    });
  };

  // 清空富文本编辑器
  clearEdit = () => {
    this.setState({
      editorState: ContentUtils.clear(this.state.editorState),
    });
  };

  render() {
    const controls: any = [
      'bold',
      'italic',
      'underline',
      'text-color',
      'separator',
      'link',
      'separator',
    ];
    const extendControls: any = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <AliyunOSSUpload
            accept="jpg,.png,.JPG,.PNG,.pdf,.PDF"
            isShowUploaded={false}
            insertImage={this.insertImage}
          >
            {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
            <Button className="control-item button upload-button" data-title="插入图片">
              插入图片
            </Button>
          </AliyunOSSUpload>
        ),
      },
    ];
    const { editorState } = this.state;
    return (
      <div className={styles.component}>
        <BraftEditor
          controls={controls}
          extendControls={extendControls}
          value={editorState}
          onChange={this.handleEditorChange}
        />
      </div>
    );
  }
}
